import numpy as np
import pandas as pd
import re, os
import colorama
import warnings
warnings.filterwarnings("ignore")
colorama.init(autoreset=True)
TEXT_COLOR_RED = colorama.Fore.RED
TEXT_COLOR_GREEN = colorama.Fore.GREEN
TEXT_COLOR_YELLOW = colorama.Fore.YELLOW
TEXT_COLOR_END = colorama.Fore.RESET
root_path=os.path.join(os.getcwd(),".\\Data_process\\Filter")
def fout(input_file_name,process_name,out_format):
    info_list=input_file_name.split(".")[0].split("-")[0].split("_")
    fout_prefix = f'{process_name}_'+"_".join(info_list[1:])
    ntry = 0
    while True:
        if ntry == 0:
            fout = fout_prefix + f'.{out_format}'
        else:
            fout = fout_prefix + '-%d.%s' % (ntry,out_format)
        if os.access(os.path.join(root_path,fout), os.F_OK):
            ntry += 1
        else:
            break
    return fout

def replace(file, replace_input):
    key = replace_input[0]
    rep_value_idx = 1
    while rep_value_idx < len(replace_input):
        info=replace_input[rep_value_idx].split(",")
        old_value = info[0]
        new_value =info[-1]
        file.loc[file[f'{key}'].round(3) == float(old_value), f'{key}'] = float(new_value)
        rep_value_idx += 1
    print(f"Finished Replacing {key}....")

def main(zf,inp_list):
    replace_bool=False
    if zf:
        n_ref=len(inp_list[0])
        consistent_bool=sum([len(file)==n_ref for file in inp_list])==len(inp_list)
        if consistent_bool:
            replace_bool=input("Find the "+TEXT_COLOR_RED+"Consistency"+TEXT_COLOR_END+" between Ref and _xx,Please Enter [yes] TO Do Replacing Only in 'Ref' File ; Else Do Replacing In Every File !\n").strip().lower()=="yes"
        else:
            replace_bool=input("Find the "+TEXT_COLOR_RED+"Inconsistency"+TEXT_COLOR_END+" between Ref and _xx,Please Enter [yes] TO Do Replacing Only in 'Ref' File ; Else Do Replaing In Every File !\n").strip().lower()=="yes"

    if replace_bool:
        print("Replacing The Ref File Only.........")
        print('Columns : %s' % (' '.join(inp_list[0].columns, )))
        nfilter=0
        while True:
            replace_input = input('Replace %d: ' % (nfilter + 1)).strip().split() # a [1,2] [2,4]
            if len(replace_input) == 0:
                break
            for idx in range(len(inp_list)):
                replace(inp_list[idx],replace_input)
            nfilter += 1
    else:
        print("Replaing The File One By One.........")
        for idx in range(len(inp_list)):
            print(f"File {idx+1} ")
            print('Columns : %s' % (' '.join(inp_list[idx].columns, )))
            nfilter = 0
            while True:
                replace_input = input('Replace %d: ' % (nfilter + 1)).strip().split()  # a [1,2] [2,4]
                if len(replace_input) == 0:
                    break
                replace(inp_list[idx],replace_input)
                nfilter+=1
    return inp_list

if __name__ == '__main__':
    root_path = os.getcwd()
    #Ref 文件必须在最前面
    finp = input('Enter data file coresponding to: Filtered_R_Ref.csv Matched_R_5.csv Matched_R_10.csv \n').strip().split()
    inp_list=[]
    for file_name in finp:
        inp = pd.read_csv(os.path.join(root_path, file_name))
        inp_list.append(inp)
    new_file=main(True,inp_list)
    for key in finp:
        replaced_fout = fout(key, "Replaced", "csv")
        new_file[finp.index(key)].to_csv(os.path.join(root_path, replaced_fout), index=False)
        print('Write output file ' + TEXT_COLOR_GREEN + "%s" % (replaced_fout,) + TEXT_COLOR_END + ' successfully!')
    # print(new_file[0]["HTL.d"]==inp_list[0]["HTL.d"])
    # print(new_file[0]["HTL.d"],"\n", inp_list[0]["HTL.d"])
# Filter_R_Ref.csv Matched_R_5.csv Matched_R_10.csv
